package com.example.ying.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.ying.common.utils.RedisKeyUtil;
import com.example.ying.common.utils.RedisUtil;
import com.example.ying.model.domain.CommentLiked;
import com.example.ying.service.CommentLikedService;
import com.example.ying.mapper.CommentLikedMapper;
import com.google.common.primitives.UnsignedInteger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CommentLikedServiceImpl extends ServiceImpl<CommentLikedMapper, CommentLiked> implements CommentLikedService {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private CommentLikedMapper commentLikedMapper;

    //通过评论id和用户id查询用户是否点赞
    @Override
    public CommentLiked existByLikedCommentIdAndLikedUserId(String likedidCommentId, String likedUserId){
        QueryWrapper<CommentLiked> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("liked_comment_id", UnsignedInteger.valueOf(likedidCommentId));
        queryWrapper.eq("liked_user_id",UnsignedInteger.valueOf(likedUserId));
        return commentLikedMapper.selectOne(queryWrapper);
    }

    //从redis获取数据并清除缓存
    @Override
    public List<CommentLiked> getLikedDataFromRedis() {
        Cursor<Map.Entry<String, Object>> cursor = redisUtil.scanCacheHash(RedisKeyUtil.MAP_KEY_COMMENT_LIKED_DETAIL, ScanOptions.NONE);
        List<CommentLiked> list = new ArrayList<>();
        while (cursor.hasNext()){
            Map.Entry<String, Object> entry = cursor.next();
            String key = entry.getKey();
            //分离出 likedCommentId，likedUserId
            String[] split = key.split("::");
            String likedCommentId = split[0];
            String likedUserId = split[1];
            Integer value = (Integer) entry.getValue();

            //组装成 CommentLiked 对象
            CommentLiked commentLike = new CommentLiked(likedCommentId, likedUserId, value);
            list.add(commentLike);

            //存到 list 后从 Redis 中删除
            redisUtil.delCacheHash(RedisKeyUtil.MAP_KEY_COMMENT_LIKED_DETAIL, key);
        }
        return list;
    }
}
